﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SimpleChatClient
{
    class Program
    {
        static bool EndOfSession = false;
        static Socket s;
        static int socketStatus;

        static void Main(string[] args)
        {
            IPAddress[] IPs = Dns.GetHostAddresses("localhost");

            s = new Socket(AddressFamily.InterNetwork,
                           SocketType.Stream,
                           ProtocolType.Tcp);

            Console.WriteLine("Establishing Connection");
            s.Connect("127.0.0.1", 7777);
            Console.WriteLine("Connection established");
            
            ThreadStart writerThreadStart = new ThreadStart(Writer);
            Thread writerThread = new Thread(writerThreadStart);
            writerThread.Start();

            ThreadStart readerThreadStart = new ThreadStart(Reader);
            Thread readerThread = new Thread(readerThreadStart);
            readerThread.Start();

            while (!EndOfSession)
            {
            }

            s.Disconnect(false);
            s.Close();

            Console.WriteLine("Session Ended");
            Console.ReadLine();

        }

        static void Reader()
        {
            byte [] buffer;
            int dataLength;

            while (!EndOfSession)
            {
                dataLength = s.Available;
                if (dataLength > 0)
                {
                    buffer = new byte[dataLength];
                    s.Receive(buffer);
                    Console.WriteLine("[RCV]{0}", Encoding.ASCII.GetString(buffer));
                }
            }

        }

        static void Writer()
        {
            string sendBuffer="";

            while (sendBuffer != "bye")
            {
                sendBuffer = Console.ReadLine();
                s.Send(Encoding.ASCII.GetBytes(sendBuffer));
            }

            EndOfSession = true;
        }

    }
}
